package com.tarena.luban.sentinel.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tarena.luban.sentinel.service.HelloService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class HelloController {
    @Autowired
    private HelloService helloService;
    @GetMapping("/hello")
    public String sayHi(String name){
        //准备一个资源的入口 Entry 资源用完了要释放
        Entry entry=null;
        try {
            //对于资源的调用取决于 entry赋值是否能通过规则的检测
            //如果SphU.entry方法检查 sayHi资源没有违反任何规则 如果违反了
            //就抛出异常,没有违反,就执行向后继续
            entry= SphU.entry("sayHi");
            String result = helloService.sayHi(name);
            return result;
        } catch (BlockException e) {
            //打印个日志
            log.info("当前资源sayHi收到了限制",e);
        } finally {
            //释放资源
            if (entry!=null) entry.exit();
        }
        return null;
    }
}
